#include "UpdateDialog.h"
#include "ui_UpdateDialog.h"
#include "UpdateWorker.h"
#include "MiscData.h"
#include "Mcu.h"

UpdateDialog *UpdateDialog::getInstance()
{
    static UpdateDialog singleton{};
    return &singleton;
}

void UpdateDialog::syncInfoSlot(int type, QString info)
{
    ui->info->setText(info);

    if (type == Error_Type) {
        ui->progress->setRange(0, 1);
        ui->progress->setValue(0);
        ui->no->setEnabled(true);
        ui->yes->setEnabled(true);
    }
}

void UpdateDialog::exeCompleteSlot()
{
    ui->info->setText(tr("升级完成，请重启机器..."));
    ui->progress->setRange(0, 1);
    ui->progress->setValue(1);
    ui->no->setEnabled(false);
    ui->yes->setEnabled(false);
}

UpdateDialog::UpdateDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UpdateDialog)
{
    ui->setupUi(this);
    QObject::connect(this, &UpdateDialog::startWorkSignal, UpdateWorker::getInstance(), &UpdateWorker::startWorkSlot);
    QObject::connect(UpdateWorker::getInstance(), &UpdateWorker::completeWorkSignal, this, &UpdateDialog::exeCompleteSlot);
    QObject::connect(UpdateWorker::getInstance(), &UpdateWorker::syncInfoSignal, this, &UpdateDialog::syncInfoSlot);
}

UpdateDialog::~UpdateDialog()
{
    delete ui;
}

void UpdateDialog::on_yes_clicked()
{
    int flag = -1;

    flag = ui->isUpdateFpga->isChecked() ? 1 : -1;
    RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateFpga = flag;

    flag = ui->isUpdateArm->isChecked() ? 1 : -1;
    RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateArm = flag;

    flag = ui->isUpdateMcu->isChecked() ? 1 : -1;
    RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateMcu = flag;

    flag = ui->isUpdateSystem->isChecked() ? 1 : -1;
    RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateSystem = flag;

    flag = ui->isUpdateLogo->isChecked() ? 1 : -1;
    RuntimeData::MiscData::getInstance()->g_miscDataInfo.isUpdateLogo = flag;

    ui->info->setText(tr("正在升级..."));
    ui->progress->setRange(0, 0);
    ui->no->setEnabled(false);
    ui->yes->setEnabled(false);

    emit startWorkSignal();
}

void UpdateDialog::on_no_clicked()
{
    ui->progress->setRange(0, 1);
    ui->progress->setValue(0);
    hide();
}
